import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_fancy_tree_view/flutter_fancy_tree_view.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:material_symbols_icons/symbols_map.dart';
import 'package:menu_bar/menu_bar.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        fontFamily: 'maple',
      ),
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: LayoutFrame());
  }
}

class WidthController extends GetxController {
  RxDouble width = 200.0.obs;

  void onDragUpdate(DragUpdateDetails details) {
    double x = details.delta.dx;
    width.value += x;
  }
}

class MyNode {
  const MyNode({
    required this.title,
    required this.icon,
    this.children = const <MyNode>[],
  });

  final String title;
  final String icon;
  final List<MyNode> children;
}

//这里是我的注释
class MyTreeTile extends StatelessWidget {
  const MyTreeTile({super.key, required this.entry, required this.onTap});

  final TreeEntry<MyNode> entry;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: TreeIndentation(
        entry: entry,
        guide: const IndentGuide.connectingLines(indent: 48),
        child: Padding(
          padding: const EdgeInsets.only(left: 4),
          child: Row(
            // 添加这个来防止Row无限扩展
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                materialSymbolsMap[entry.node.icon] ?? Icons.folder,
                size: 24,
              ),
              // 使用Flexible包裹Text，允许文本在需要时换行
              Flexible(
                child: Text(
                  entry.node.title,
                  // 防止文本溢出
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class LeftNavigation extends StatefulWidget {
  const LeftNavigation({super.key});

  @override
  State<LeftNavigation> createState() => _LeftNavigationState();
}

class _LeftNavigationState extends State<LeftNavigation> {
  static const List<MyNode> roots = <MyNode>[
    MyNode(
      title: 'Mysql',
      icon: 'directions_bus_filled_sharp',
      children: <MyNode>[
        MyNode(
          title: '逻辑数据库',
          icon: 'home',
          children: <MyNode>[
            MyNode(
              title: '数据表',
              icon: 'table_view_sharp',
              children: <MyNode>[],
            ),
          ],
        ),
      ],
    ),
    MyNode(
      title: 'Sqlite',
      icon: 'pedal_bike_sharp',
      children: <MyNode>[MyNode(title: '数据表', icon: 'table_view_sharp')],
    ),
  ];

  late final TreeController<MyNode> treeController;

  @override
  void initState() {
    super.initState();
    treeController = TreeController<MyNode>(
      roots: roots,
      childrenProvider: (MyNode node) => node.children,
    );
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: double.infinity,
      child: TreeView<MyNode>(
        treeController: treeController,
        nodeBuilder: (BuildContext context, TreeEntry<MyNode> entry) {
          return MyTreeTile(
            key: ValueKey(entry.node),
            entry: entry,
            onTap: () => treeController.toggleExpansion(entry.node),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    treeController.dispose();
    super.dispose();
  }
}

class LayoutFrame extends StatelessWidget {
  const LayoutFrame({super.key});

  @override
  Widget build(BuildContext context) {
    var c = Get.put(WidthController());
    return Column(
      children: [
        SizedBox(
          height: 40,
          child: MenuBarWidget(
            barStyle: MenuStyle(
              backgroundColor: WidgetStateProperty.all(const Color(0xFF5E9BF0)),
            ),
            barButtons: [
              BarButton(
                text: const Text('文件', style: TextStyle(color: Colors.white)),
                submenu: SubMenu(
                  menuItems: [
                    MenuButton(
                      text: const Text('新建'),
                      onTap: () {
                        print('saved');
                      },
                      icon: const Icon(Icons.save),
                      shortcutText: 'Ctrl+S',
                    ),
                    const MenuDivider(),
                    MenuButton(
                      text: const Text('连接'),
                      onTap: () {},
                      icon: const Icon(Icons.exit_to_app),
                      shortcutText: 'Ctrl+Q',
                    ),
                    MenuButton(
                      text: const Text('数据库'),
                      onTap: () {},
                      icon: const Icon(Icons.exit_to_app),
                      shortcutText: 'Ctrl+Q',
                    ),
                  ],
                ),
              ),
              BarButton(
                text: const Text('Help', style: TextStyle(color: Colors.white)),
                submenu: SubMenu(
                  menuItems: [
                    MenuButton(text: const Text('View License'), onTap: () {}),
                    MenuButton(
                      text: const Text('About'),
                      onTap: () {},
                      icon: const Icon(Icons.info),
                    ),
                  ],
                ),
              ),
            ],
            child: Container(),
          ),
        ),
        Expanded(
          child: Row(
            children: [
              Obx(
                () => SizedBox(
                  width: c.width.value,
                  // 使用 Expanded 或 SizedBox 包裹 SingleChildScrollView，提供垂直方向的约束
                  child: ScrollConfiguration(
                    behavior: ScrollConfiguration.of(
                      context,
                    ).copyWith(scrollbars: true),
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: SizedBox(
                        width: max(200.0, c.width.value),
                        // 确保 LeftNavigation 填充整个高度
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                            minHeight: MediaQuery.of(context).size.height,
                          ),
                          child: IntrinsicHeight(child: LeftNavigation()),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              GestureDetector(
                onHorizontalDragUpdate: (details) {
                  c.onDragUpdate(details);
                },
                child: MouseRegion(
                  cursor: SystemMouseCursors.resizeLeftRight,
                  child: VerticalDivider(
                    color: Colors.pink,
                    width: 5,
                    thickness: 1,
                  ),
                ),
              ),
              Expanded(
                child: Obx(
                  () => Container(
                    width: MediaQuery.of(context).size.width - c.width.value,
                    child: Center(
                      child: Text(
                        '${MediaQuery.of(context).size.width - c.width.value}',
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
